package com.example.demo.jwt;

import com.example.demo.security.service.MyUserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class JwtAuthService {

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    MyUserDetail myUserDetail;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    public String login(String username,String password) throws Exception {
       try {
           UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,password);
           Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
           SecurityContextHolder.getContext().setAuthentication(authentication);
       }catch (Exception e){
          throw  new Exception("账号密码错误");
       }
       return jwtTokenUtil.generateToken(myUserDetail.loadUserByUsername(username));
    }
}

